package org.ssh2.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.ssh2.annotation.LogMsg;
import org.ssh2.common.Const;
import org.ssh2.core.entity.SoftClassroom;
import org.ssh2.core.entity.SoftRole;
import org.ssh2.core.entity.SoftUser;
import org.ssh2.core.service.IClassroomService;
import org.ssh2.core.service.IProjectService;
import org.ssh2.core.service.IRoleService;
import org.ssh2.core.service.IUserService;
import org.ssh2.core.service.impl.ProjectServiceImpl;
import org.ssh2.core.util.Page;
import org.ssh2.util.DateUtils;
import org.ssh2.web.AbstractBaseController;
import org.ssh2.web.struts2.vo.Result;

import com.opensymphony.xwork2.util.CreateIfNull;
import com.opensymphony.xwork2.util.Element;
import com.opensymphony.xwork2.util.KeyProperty;

public class UserController extends AbstractBaseController {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7825266525716947869L;

	public SoftUser user;

	/**
	 * 配置页面传值映射
	 */

	@Element(org.ssh2.core.entity.SoftRole.class)
	@KeyProperty("id")
	@CreateIfNull(true)
	public Set<SoftRole> roles = new HashSet<SoftRole>();

	@Element(org.ssh2.core.entity.SoftClassroom.class)
	@KeyProperty("id")
	@CreateIfNull(true)
	public Set<SoftClassroom> classrooms = new HashSet<SoftClassroom>();

	public String[]  classroomId;
	
	public Set<SoftClassroom> getClassrooms() {
		return classrooms;
	}

	public void setClassrooms(Set<SoftClassroom> classrooms) {
		this.classrooms = classrooms;
	}

	public String[] getClassroomId() {
		return classroomId;
	}

	public void setClassroomId(String[] classroomId) {
		this.classroomId = classroomId;
	}

	private List<Integer> ids;//	获取复选框的值

	@Resource(name = "userService")
	private IUserService userService;
	@Resource(name = "roleService")
	private IRoleService roleService;

	@Resource(name = "projectService")
	private IProjectService projectService;

	@Resource(name = "classroomService")
	private IClassroomService classroomService;


	public IClassroomService getClassroomService() {
		return classroomService;
	}

	public void setClassroomService(IClassroomService classroomService) {
		this.classroomService = classroomService;
	}

	public List<Integer> getIds() {
		return ids;
	}

	public void setIds(List<Integer> ids) {
		this.ids = ids;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public IRoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(IRoleService roleService) {
		this.roleService = roleService;
	}



	public IProjectService getProjectService() {
		return projectService;
	}

	public void setProjectService(IProjectService projectService) {
		this.projectService = projectService;
	}

	@LogMsg(msg ="登录失败")
	public String loginPrompt(){
		setPrompt("/login.jsp");
		System.out.println("密码错误");
		return SUCCESS;
	}

	@LogMsg(msg = "用户登陆")
	public String doLogin(){
		System.out.println("doLogin()被执行了");
		System.out.println(",,");
		//setPrompt("test.jsp");
		setPrompt("/WEB-INF/pages/main.jsp");
		System.out.println("用户登陆");
		System.out.println("ssssssss");
		return SUCCESS;

	}

	/**
	 * 跳转到添加用户页面
	 * 解决方式就是用getAllFromTable把角色信息 班级用list查出来然后把他们放入session
	 * 到添加页面用list遍历出来
	 * 12月6日
	 * @return String
	 */
	@LogMsg(msg = "用户toAdd")
	public String toAdd(){
		List<SoftRole> list = roleService.getAllFromTable();
		List<SoftClassroom> classroomList = classroomService.getAllFromTable();
		System.out.println("classroomList"+classroomList);
		request.put("classroomList", classroomList);
		request.put("list", list);
		String msg = (String) session.get("msg");
		session.remove("msg");//是删除session中“msg”对应的值
		if(msg != null){
			request.put("msg", msg);//放入
		}
		setPrompt("/WEB-INF/pages/user/user_add.jsp");
		return SUCCESS;

	}
	/**
	 *  分页
	 *  
	 *  查询用户信息管理
	 * @return
	 */
	public String listPrompt(){		
		Page<SoftUser> page = new Page<SoftUser>(); //创建分页对象指定泛型		
		page.setOnePageNum(10); //设置单页记录数 默认5		
		page.setPageNo(pageNo==null?1:pageNo); //设置当前页数 默认1
		page.setClazz("User");
		userService.findForPage(page);		
		request.put("page", page);		
		setPrompt("/WEB-INF/pages/user/user_list.jsp");
		return SUCCESS;
	}

	/**
	 * 退出登陆
	 * @return
	 */
	public String doLogout(){
		session.clear(); // 清除session
		session.put("msg", Const.LOGOUT_MSG);	// 重定向不能把信息放到request中
		setPrompt("User_loginPrompt.action"); 
		System.out.println("退出登"+"''' "+session);
		
		return "reposition";
	}
	/**
	 * 检查用户名是否存在
	 * @return
	 * @throws IOException 
	 */
	public void checkName(){
		
		Result result = new Result();
		result.setCode(1);
		SoftUser u = userService.findByUserName(user.getUserName());
		if(u!=null){
			result.setCode(0);
			result.setMsg("名字已存在！");
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(gson.toJson(result));
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(writer!=null){
		        writer.close();
			}
		}

	}
	
	/**
	 * 添加用户
	 * 是把外键的添加传进来
	 * 时间获取
	 * 
	 * @return
	 */
	@LogMsg(msg="添加用户")
	public String addUser(){
		System.out.println("执行了addUser()");
      	user.setUser_role(roles);
		System.out.println("roles="+roles);
		System.out.println("classroomId="+classroomId);
		System.out.println("classrooms="+classrooms);
		user.setUser_classroom(classrooms);
		user.setCreateDate(DateUtils.getCurrentDate());
		userService.save(user);
		setPrompt("/WEB-INF/pages/main.jsp");
		return SUCCESS;

	}
	@LogMsg(msg="更新用户")
	public String doUpdate(){
		user.setUser_role(roles);
		userService.updateById(user);
		session.put("msg", "更新成功！");
		setPrompt("User_updatePrompt.action?user.userName="+user.getUserName());
		return "reposition";
	}

	@LogMsg(msg="批量删除用户")
	public String doBatchDelete(){
		userService.batchDelete(ids);
		setPrompt("User_listPrompt.action");
		return "reposition";
	}
	@LogMsg(msg="跳转更新页面")
	public String updatePrompt(){
		//查找要修改的用户信息
		SoftUser us = userService.findByUserName(user.getUserName());
		//查找所有角色
		List<SoftRole> list = roleService.getAllFromTable();
		//去掉用户已有的角色
		for (int i=0;i<list.size();i++) {
			if(us.getUser_role().contains(list.get(i))){
				list.remove(list.get(i));
				i--;
			}

		}
		
		String msg = (String) session.get("msg");
		session.remove("msg");
		if(msg!=null){
			request.put("msg", msg);
		}
		request.put("list", list);
		request.put("user", us);
		setPrompt("/WEB-INF/pages/user/user_update.jsp");
		return SUCCESS;
	}
	public String passwordMD5(){
		return SUCCESS;
		
	}
	public SoftUser getUser() {
		return user;
	}

	public void setUser(SoftUser user) {
		this.user = user;
	}

	public Set<SoftRole> getRoles() {
		return roles;
	}

	public void setRoles(Set<SoftRole> roles) {
		this.roles = roles;
	}

}
